﻿using GameStoreMinimalApi.WebApi.Repositories;
using Microsoft.EntityFrameworkCore;

namespace GameStoreMinimalApi.WebApi.Data;

public static class DataExtensions
{
    public static async Task InitializeDbAsync(this IServiceProvider serviceProvider)
    {
        using var scope = serviceProvider.CreateScope();

        var dbContext = scope.ServiceProvider.GetRequiredService<GameStoreDbContext>();
        await dbContext.Database.MigrateAsync();

        var logger = serviceProvider.GetRequiredService<ILoggerFactory>()
                                    .CreateLogger("DB Initializer");

        logger.LogInformation(5, "The DB is ready.");
    }

    public static IServiceCollection AddRepositories(this IServiceCollection services, IConfiguration configuration)
    {
        var connectionString = configuration.GetConnectionString("GameStoreContext");
        services.AddNpgsql<GameStoreDbContext>(connectionString)
                .AddScoped<IGamesRepository, EFGamesRepository>();

        return services;
    }
}
